package com.lfd.springasync.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

/**
 * @项目名： spring-emq
 * @包名： com.lfd.springasync.service
 * @文件名: AsyncService
 * @创建者: liufudong@szyh-smart.com
 * @创建时间: 2024/10/13 21:21
 * @描述：
 */
@Slf4j
@Service
public class AsyncService {

//    AsyncController调用异步方法开始http-nio-8076-exec-2
//    AsyncService异步方法开始执行
//    AsyncService异步方法执行完毕http-nio-8076-exec-2
//    AsyncController调用异步方法结束http-nio-8076-exec-2

    //    AsyncController调用异步方法开始http-nio-8076-exec-1
//    AsyncController调用异步方法结束http-nio-8076-exec-1
//    AsyncService异步方法开始执行
//    AsyncService异步方法执行完毕task-1
    @Async
    public void asyncMethod() {
        try {
            log.info("AsyncService异步方法开始执行");
            // 模拟耗时任务
            Thread.sleep(2000);
            log.info("AsyncService异步方法执行完毕" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Async
    public Future<String> asyncMethodWithReturn() {
        try {
            log.info("AsyncService asyncMethodWithReturn 异步方法开始执行");
            Thread.sleep(2000);
//            int i =2/0;
            log.info("AsyncService asyncMethodWithReturn 异步任务完成");
            return CompletableFuture.completedFuture("异步任务完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.info("AsyncService asyncMethodWithReturn 任务异常");
            return CompletableFuture.completedFuture("任务异常");
        }
    }
    @Async("taskExecutor")  // 使用自定义的 taskExecutor 线程池
    public void asyncMethodExecutor() {
        // 异步执行的代码
        try {
            log.info("asyncMethodExecutor 异步方法开始执行");
            // 模拟耗时任务
            Thread.sleep(2000);
            log.info("asyncMethodExecutor 异步方法执行完毕" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Async("taskExecutor")  // 使用自定义的 taskExecutor 线程池
    public void asyncMethodExecutor2() {
        // 异步执行的代码
        try {
            log.info("asyncMethodExecutor2 异步方法开始执行");
            // 模拟耗时任务
            int i=1/0;
            Thread.sleep(2000);
            log.info("asyncMethodExecutor2 异步方法执行完毕" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
